package com.zhixing.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.zhixing.common.constant.Constant;
import com.zhixing.common.domain.entity.UserInfo;
import com.zhixing.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验user-info
        UserInfo userInfo = JSON.parseObject(request.getHeader(Constant.USER_INFO), UserInfo.class);
        if (ObjectUtil.isEmpty(userInfo)) return false;

        // 存入ThreadLocal
        UserContext.setUserInfo(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal
        UserContext.remove();
    }
}
